package com.my_musc_service.config;

import com.my_musc_service.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    private static final Integer YEAR=2020;


    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePathlist = new ArrayList<>();
        excludePathlist.add("/login");
        excludePathlist.add("/register");
        excludePathlist.add("/images/**");
        excludePathlist.add("/html/**");
        int currentYear = LocalDateTime.now().getYear();
        for (int i = 0; i <= (currentYear - YEAR); i++) {
            excludePathlist.add( "/" + (YEAR+i) + "/**");
        }

        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                //放行
                .excludePathPatterns(excludePathlist);
    }


    /**
     * 解决cors跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .maxAge(30 * 1000);
    }
}
